package org.edu.modules.system.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.edu.common.api.vo.Result;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.system.entity.VeBaseAppUser;
import org.edu.modules.system.entity.VeBaseUserAccess;
import org.edu.modules.system.mapper.VeBaseAppUserMapper;
import org.edu.modules.system.service.IVeBaseAppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VeBaseAppUserServiceImpl extends ServiceImpl<VeBaseAppUserMapper, VeBaseAppUser> implements IVeBaseAppUserService {

    @Autowired
    private VeBaseAppUserMapper veBaseAppUserMapper;

    public VeBaseAppUser getUserByPhone(String phone) {
        return this.veBaseAppUserMapper.getUserByPhone(phone);
    }

    public VeBaseAppUser getUserByName(String userName) {
        return this.veBaseAppUserMapper.getUserByName(userName);
    }

    public VeBaseAppUser getAppUserByUserId(String userId) {
        return this.veBaseAppUserMapper.getUserByUserId(userId);
    }

    public List<Map<String, Object>> getBaseSysRoleList(String userId, String appId) {
        return this.veBaseAppUserMapper.getBaseSysRoleList(userId, appId);
    }

    public List<Map<String, Object>> getBaseSysMenuList(String userId, String appId, String roleId) {
        List<Map<String, Object>> rootList = new ArrayList<>();
        List<Map<String, Object>> bodyList = this.veBaseAppUserMapper.getBaseSysMenuList(userId, appId, roleId);
        if (bodyList.size() > 1) {
            for (Map<String, Object> map1 : bodyList) {
                if (Integer.parseInt(map1.get("pid").toString()) < 0)
                    rootList.add(map1);
            }
            Map<String, String> map = new HashMap<>();
            rootList.forEach(menu -> getChild(menu, map, userId, appId, roleId));
            return rootList;
        }
        return rootList;
    }

    public List<Map<String, Object>> getBaseAppManageList(String userId, String appId, String roleId) {
        return this.veBaseAppUserMapper.getBaseAppManageList(userId, appId, roleId);
    }

    public List<Map<String, Object>> getBaseServiceList(String userId) {
        return this.veBaseAppUserMapper.getBaseServiceList(userId);
    }

    public VeBaseAppUser getUserByToken(String token) {
        return this.veBaseAppUserMapper.getUserByToken(token);
    }

    public Result<?> getSrategy(String userId) {
        Result<?> result = new Result();
        Date date = new Date();
        SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        String times = simpleDateFormat.format(date);
        List<Map<String, Object>> dateList = this.veBaseAppUserMapper.getDateSrategyByTime(times);
        int number = 0;
        if (dateList.size() > 0)
            number = 1;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            String ipName = ip.toString().replaceAll("[^0-9\\.]", "");
            String[] ips = ipName.split("\\.");
            Long num = Long.valueOf(0L);
            if (ips.length == 4) {
                num = Long.valueOf(Long.parseLong(ips[0], 10) * 256L * 256L * 256L + Long.parseLong(ips[1], 10) * 256L * 256L + Long.parseLong(ips[2], 10) * 256L + Long.parseLong(ips[3], 10));
                num = Long.valueOf(num.longValue() >>> 0L);
            }
            List<Map<String, Object>> ipList = this.veBaseAppUserMapper.getIpSrategyByIp(num);
            if (ipList.size() > 0)
                number = 2;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        VeBaseUserAccess veBaseUserAccess = this.veBaseAppUserMapper.getAfterUserAccessModel(userId);
        if (veBaseUserAccess != null)
            if (!"".equals(veBaseUserAccess.getStatus()) && veBaseUserAccess.getStatus().equals("9999") &&
                    !"".equals(veBaseUserAccess.getUpdateTime()) && veBaseUserAccess.getUpdateTime() != null) {
                DateTime dateTime1 = DateUtil.parse(times);
                DateTime dateTime2 = DateUtil.parse(veBaseUserAccess.getUpdateTime().toString());
                if (dateTime1.getTime() < dateTime2.getTime())
                    number = 4;
            }
        if (number != 0) {
            String ss = null;
            if (number == 1) {
                ss = "该时间段不能登录";
            } else if (number == 2) {
                ss = "该IP地址不能登录";
            } else if (number == 4) {
                if (veBaseUserAccess != null && !"".equals(veBaseUserAccess.getStatus()) && veBaseUserAccess.getStatus().equals("9999") && !"".equals(veBaseUserAccess.getUpdateTime()) && veBaseUserAccess.getUpdateTime() != null) {
                    ss = "登录失败次数过多暂时不能登录，请于" + sdt.format(veBaseUserAccess.getUpdateTime()) + "之后再行登录";
                } else {
                    ss = "登录失败次数过多暂不能登录";
                }
            } else if (number == 3) {
                ss = "该时间段不能登录，该IP地址不能登录";
            } else if (number == 5) {
                ss = "该时间段不能登录,登录失败次数过多暂不能登录，请于" + sdt.format(veBaseUserAccess.getUpdateTime()) + "之后再行登录";
            } else if (number == 6) {
                ss = "该ip地址不能登录，登录失败次数过多暂不能登录，请于" + sdt.format(veBaseUserAccess.getUpdateTime()) + "之后再行登录";
            } else if (number == 7) {
                ss = "该时间段不能登录，该IP地址不能登录，登录失败次数过多暂不能登录，请于" + sdt.format(veBaseUserAccess.getUpdateTime()) + "之后再行登录";
            }
            if (ss != null) {
                result.setMessage(ss);
                result.error500(ss);
            }
        }
        return result;
    }

    public Result addUserAccessAndGetMessage(String userId, String password) {
        Result<?> result = new Result();
        StringBuilder stringBuilder = new StringBuilder();
        List<Map<String, Object>> loginList = this.veBaseAppUserMapper.getLoginSrategyList();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dt = new Date();
        stringBuilder.append("用户名或密码错误");
        String local = "";
        try {
            InetAddress ip = InetAddress.getLocalHost();
            local = ip.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String id = UUID.randomUUID().toString().replace("-", "");
        VeBaseAppUser veBaseAppUser = this.veBaseAppUserMapper.getUserByUserId(userId);
        if (loginList.size() > 0) {
            Long times = Long.valueOf(DateUtil.parse(simpleDateFormat.format(dt)).getTime());
            Double time_diff = Double.valueOf(Double.parseDouble(((Map) loginList.get(0)).get("timeDiff").toString()) * 60.0D * 1000.0D);
            Long a = Long.valueOf(times.longValue() - time_diff.longValue());
            Date d_times = new Date(a.longValue());
            String stimes = simpleDateFormat.format(d_times);
            List<Map<String, Object>> list = this.veBaseAppUserMapper.getUserAccessByUsername(userId, stimes);
            List<Map<String, Object>> mapList = new ArrayList<>();
            if (list.size() == 0) {
                this.veBaseAppUserMapper.addUserAccess(id, userId, local, veBaseAppUser.getUserName(), password);
            } else {
                for (Map<String, Object> map : list) {
                    if (map.get("opr").toString().equals("0") && map.get("status").toString().equals("9999"))
                        mapList.add(map);
                }
                int errorCount = Integer.parseInt(((Map) loginList.get(0)).get("errorCount").toString());
                if (mapList.size() > 0 && mapList.size() == errorCount - 1) {
                    Long bt = Long.valueOf(time_diff.longValue() + times.longValue());
                    Date bt_times = new Date(bt.longValue());
                    String btimes = simpleDateFormat.format(bt_times);
                    this.veBaseAppUserMapper.addUserAccessUpdateTime(id, userId, local, veBaseAppUser.getUserName(), password, btimes);
                    stringBuilder.append(", 请于" + btimes + "之后再进行登录");
                } else {
                    this.veBaseAppUserMapper.addUserAccess(id, userId, local, veBaseAppUser.getUserName(), password);
                }
            }
        } else {
            this.veBaseAppUserMapper.addUserAccess(id, userId, local, veBaseAppUser.getUserName(), password);
        }
        result.setMessage(stringBuilder.toString());
        result.setCode(Integer.valueOf(500));
        return result;
    }

    public Result<?> getSysRoleByUserIdAndAppId(String userId, String appId) {
        Result<?> result = new Result();
        List<Map<String, Object>> list = this.veBaseAppUserMapper.getSysRoleByUserIdAndAppId(userId, appId);
        if (list == null || list.size() == 0)
//            result.error500("没有角色无法登录");//20250120 lbh 角色权限配置有问题，暂时撤销角色权限判断
            result.success("没有角色");
        return result;
    }

    public int addUserAccess(String userId, String pwd, String userName, String opr, String status) {
        String local = "";
        try {
            InetAddress ip = InetAddress.getLocalHost();
            local = ip.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return this.veBaseAppUserMapper.addUserAccessSucceed(userId, pwd, userName, opr, status, local);
    }

    public Map getTeacherByUserId(String userId) {

        return this.veBaseAppUserMapper.getTeacherByUserId(userId);
    }

    public Map getTeacherByGH(String gh) {

        return this.veBaseAppUserMapper.getTeacherByGH(gh);
    }

    public Map getStudentByUserId(String userId) {

        return this.veBaseAppUserMapper.getStudentByUserId(userId);
    }

    public Map getStudentByXH(String xh) {

        return this.veBaseAppUserMapper.getStudentByXH(xh);
    }

    @Override
    public Map getTeacherDeatilByGH(String gh) {
        return this.veBaseAppUserMapper.getTeacherDeatilByGH(gh);
    }

    @Override
    public Map getStudentDeatilByXH(String xh) {
        return this.veBaseAppUserMapper.getStudentDeatilByXH(xh);
    }

    public VeBaseAppUser getAppUserByUsername(String username) {
        if (oConvertUtils.isEmpty(username))
            return null;
        VeBaseAppUser veBaseAppUser = this.veBaseAppUserMapper.getUserByUserId(username);
        if (veBaseAppUser == null)
            return null;
        if (!"".equals(veBaseAppUser.getUserType()) && veBaseAppUser.getUserType() != null) {
            if (veBaseAppUser.getUserType().contains("1")) {
                Map map = this.veBaseAppUserMapper.getTeacherByUserId(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                }
            } else if (veBaseAppUser.getUserType().contains("2")) {
                Map map = this.veBaseAppUserMapper.getStudentByUserId(veBaseAppUser.getUserId());
                if (map != null) {
                    veBaseAppUser.setTeacherOrStudentId(map.get("id").toString());
                } else {
                    veBaseAppUser.setTeacherOrStudentId("");
                }
            } else {
                veBaseAppUser.setTeacherOrStudentId("");
            }
        } else {
            veBaseAppUser.setTeacherOrStudentId("");
        }
        return veBaseAppUser;
    }

    public List<Map<String, Object>> getVeBaseSysConfig() {

        return this.veBaseAppUserMapper.getVeBaseSysConfig();
    }

    public List<Map<String, Object>> queryVeBaseDictionary() {
        List<Map<String, Object>> list = this.veBaseAppUserMapper.queryVeBaseDictionary();
        List<Map<String, Object>> detailList = this.veBaseAppUserMapper.queryVeBaseData();
        for (Map<String, Object> map : list) {
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (Map<String, Object> detail : detailList) {
                if (!"".equals(map.get("code")) && map.get("code") != null && !"".equals(detail.get("modelCode")) && detail.get("modelCode") != null && map.get("code").equals(detail.get("modelCode")))
                    mapList.add(detail);
            }
            map.put("detailList", mapList);
        }
        return list;
    }

    public Result getAppManageByAppId(String appId) {
        Result result = new Result();
        Map map = this.veBaseAppUserMapper.getAppManageByAppId(appId);
        if (map == null)
            result.error500("应用不存在或已被禁用");
        return result;
    }



    public void getChild(Map<String, Object> menu, Map<String, String> map, String userId, String appId, String roleId) {
        List<Map<String, Object>> bodyList = this.veBaseAppUserMapper.getBaseSysMenuList(userId, appId, roleId);
        List<Map<String, Object>> childList = new ArrayList<>();
        bodyList.stream().filter(c -> !map.containsKey(c.get("id"))).filter(c -> c.get("pid").toString().equals(menu.get("id").toString()))
                .forEach(c -> {
                    map.put(c.get("id").toString(), c.get("pid").toString());
                    getChild(c, map, userId, appId, roleId);
                    childList.add(c);
                });
        menu.put("childList", childList);
    }


 /*   public void getChild(Map<String, List<Map<String, Object>>> menu, Map<String, String> map, String userId, String appId, String roleId) {
        List<Map<String, Object>> bodyList = this.veBaseAppUserMapper.getBaseSysMenuList(userId, appId, roleId);
        List<Map<String, Object>> childList = new ArrayList<>();
        bodyList.stream().filter(c -> !map.containsKey(c.get("id"))).filter(c -> c.get("pid").toString().equals(menu.get("id").toString()))
                .forEach(c -> {
                    map.put(c.get("id").toString(), c.get("pid").toString());
                    getChild(c, map, userId, appId, roleId);
                    childList.add(c);
                });
        menu.put("childList", childList);
    }*/


}
